#include "Updater.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <cstdio>

Updater::Updater()
{
	getCurrentVersions();
}

Updater::~Updater()
{
	curl_easy_cleanup(curl);
}

int Updater::checkForUpdates()
{
	curl = curl_easy_init();
	curl_easy_setopt(curl,CURLOPT_URL,"http://fortressoverseer.googlecode.com/hg/VERSION");
	curl_easy_setopt(curl,CURLOPT_HEADER,0);	
	curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,getLatestVersions);
	curl_easy_setopt(curl,CURLOPT_WRITEDATA,&latestVersions);
	
	CURLcode result = curl_easy_perform(curl);

	if (result == CURLE_OK)
	{
		int versplit = latestVersions.find(" "), minsplit = latestVersions.rfind(" "), status = 0;
		if (currentOverseer!=latestVersions.substr(0,versplit)) status |=2;
		if (currentDF!=latestVersions.substr(versplit+1,minsplit-(versplit+1)))
		{
			int vercomp = currentOverseer.compare(latestVersions.substr(minsplit+1));
			if (vercomp >= 0) status |=1;
			else status |= 4;
		}

		return status;
	}

	return 0;
}

bool Updater::updateMemoryXML()
{
	curl = curl_easy_init();
	curl_easy_setopt(curl,CURLOPT_URL,"http://fortressoverseer.googlecode.com/hg/Memory.xml");
	FILE *memoryxml = fopen("Memory.xml","wb");
	curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writeMemoryXML);
	curl_easy_setopt(curl,CURLOPT_WRITEDATA,memoryxml);
	CURLcode result = curl_easy_perform(curl);

	if (result == CURLE_OK)
	{
		std::ofstream vfile("VERSION",std::ofstream::out);
		vfile << currentOverseer << " " << latestVersions.substr(latestVersions.find(" ")+1) << std::endl;
		return true;
	}
	else return false;
}

size_t Updater::getLatestVersions(char *data, size_t size, size_t nmemb, std::string *buffer)
{
	if (buffer!=NULL)
	{
		buffer->append(data, size*nmemb);
		return size*nmemb;
	}
	return 0;
}

size_t Updater::writeMemoryXML(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
	return fwrite(ptr,size,nmemb,stream);
}

bool Updater::getCurrentVersions()
{
	std::ifstream vfile("VERSION",std::ifstream::in);
	if (vfile.good())
	{
		vfile >> currentOverseer;
		vfile >> currentDF;
		return true;
	}
	return false;
}